import { ref, watch } from 'vue'
import { defineStore } from 'pinia'

// 收藏项接口
export interface FavoriteItem {
  id: string | number
  title: string
  description?: string
  playUrl?: string
  cover?: string
  author: {
    name: string
    icon?: string
  }
  duration?: number
  favoritedAt: number // 收藏时间戳
  tags?: Array<{ name: string }>
  consumption?: {
    collectionCount?: number
    realCollectionCount?: number
    replyCount?: number
    shareCount?: number
  }
}

const MAX_FAVORITES_COUNT = 100

// 从本地存储加载数据
const loadFromStorage = (): FavoriteItem[] => {
  try {
    const currentPhone = localStorage.getItem('currentPhoneNumber')
    if (!currentPhone) {
      return []
    }

    const users = JSON.parse(localStorage.getItem('users') || '[]')
    const user = users.find((u: any) => u.phoneNumber === currentPhone)

    if (user && user.favorites && Array.isArray(user.favorites)) {
      return user.favorites
    }
    return []
  } catch (error) {
    console.error('加载收藏列表失败:', error)
    return []
  }
}

// 保存到本地存储
const saveToStorage = (favorites: FavoriteItem[]) => {
  try {
    const currentPhone = localStorage.getItem('currentPhoneNumber')
    if (!currentPhone) {
      return
    }

    const users = JSON.parse(localStorage.getItem('users') || '[]')
    const userIndex = users.findIndex((u: any) => u.phoneNumber === currentPhone)

    if (userIndex !== -1) {
      users[userIndex].favorites = favorites
      localStorage.setItem('users', JSON.stringify(users))
    } else {
      // 如果用户不存在，创建新用户对象
      const newUser = {
        phoneNumber: currentPhone,
        favorites: favorites
      }
      users.push(newUser)
      localStorage.setItem('users', JSON.stringify(users))
    }
  } catch (error) {
    console.error('保存收藏列表失败:', error)
  }
}

export const useFavoritesStore = defineStore('favorites', () => {
  // 收藏列表数组
  const favoritesList = ref<FavoriteItem[]>([])

  // 从本地存储加载数据
  const loadFavorites = () => {
    favoritesList.value = loadFromStorage()
  }

  // 保存到本地存储
  const saveFavorites = () => {
    saveToStorage(favoritesList.value)
  }

  // 添加收藏
  const addFavorite = (video: any) => {
    if (!video || !video.id) return false

    // 检查是否已收藏
    const existingIndex = favoritesList.value.findIndex(item => item.id === video.id)
    if (existingIndex !== -1) {
      // 已收藏，返回 false
      return false
    }

    // 获取封面图片
    let coverUrl = ''
    if (typeof video.cover === 'string') {
      coverUrl = video.cover
    } else if (video.cover) {
      coverUrl = video.cover.feed || video.cover.detail || video.cover.blurred || ''
    }

    // 构建收藏项
    const favoriteItem: FavoriteItem = {
      id: video.id,
      title: video.title || '',
      description: video.description,
      playUrl: video.playUrl,
      cover: coverUrl,
      author: {
        name: video.author?.name || '未知',
        icon: video.author?.icon
      },
      duration: video.duration || 0,
      favoritedAt: Date.now(),
      tags: video.tags,
      consumption: video.consumption
    }

    // 添加到数组最前面
    favoritesList.value.unshift(favoriteItem)

    // 如果超过最大数量，删除最后一项
    if (favoritesList.value.length > MAX_FAVORITES_COUNT) {
      favoritesList.value = favoritesList.value.slice(0, MAX_FAVORITES_COUNT)
    }

    // 自动保存到本地存储
    saveFavorites()
    return true
  }

  // 取消收藏
  const removeFavorite = (videoId: string | number) => {
    const index = favoritesList.value.findIndex(item => item.id === videoId)
    if (index !== -1) {
      favoritesList.value.splice(index, 1)
      saveFavorites()
      return true
    }
    return false
  }

  // 检查是否已收藏
  const isFavorited = (videoId: string | number): boolean => {
    return favoritesList.value.some(item => item.id === videoId)
  }

  // 切换收藏状态
  const toggleFavorite = (video: any) => {
    if (!video || !video.id) return false

    if (isFavorited(video.id)) {
      return removeFavorite(video.id)
    } else {
      return addFavorite(video)
    }
  }

  // 清空收藏列表
  const clearFavorites = () => {
    favoritesList.value = []
    saveFavorites()
  }

  // 监听登录状态变化，重新加载数据
  const handleLoginChange = () => {
    loadFavorites()
  }

  // 初始化：从本地存储加载
  loadFavorites()

  // 监听 localStorage 中 currentPhoneNumber 的变化
  if (typeof window !== 'undefined') {
    window.addEventListener('storage', (e) => {
      if (e.key === 'currentPhoneNumber') {
        loadFavorites()
      }
    })
  }

  return {
    favoritesList,
    addFavorite,
    removeFavorite,
    isFavorited,
    toggleFavorite,
    clearFavorites,
    loadFavorites,
    handleLoginChange
  }
})

